import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Modal } from 'antd';
import PropTypes from 'prop-types';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import AddModel from './addModel';
import ExportModal from './exportModel';
import { filterAuth } from '@/support/common';
import BindModel from './bindModel';
import ConfirmDelModal from './confirmDelModal';
import UnbindModel from './unbindModel';

const mapStateToProps = (state: any) => ({
  VehicleMng: state.VehicleMng,
  loading: state.loading.models['VehicleMng'],
  permissions: state?.menu?.permissions,
  user: state?.menu?.userProfile,
});
class VehicleMng extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      modalVisible: false,
      formData: {},
      exportVisible: false,
      BindModalVisible: false,
      unBindVisible: false,
      confirmVisible: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'VehicleMng/getFetchPage',
      payload: {
        url: '/msalcohollock/vehicle/page',
        ...formValues,
      },
    });
  }
  handleFormReset = (fields: any) => {
    this.setState({
      formValues: {},
    });
  };
  //  新增
  handleAdd = () => {
    this.setState({
      modalVisible: true,
    });
  };

  //  编辑
  handleEdit = (data: any) => {
    // const { sid, vin, happenDate, address, status, remark } = data;
    this.setState({
      modalVisible: true,
      formData: data,
    });
  };
  closeModal = () => {
    this.setState({
      modalVisible: false,
      formData: {},
    });
  };
  //绑定设备
  handleBind = (data: any) => {
    this.setState({
      bindModalVisible: true,
      formData: {
        ...data,
      },
    });
  };
  closeBindModal = () => {
    this.setState({
      bindModalVisible: false,
      formData: {},
    });
  };
  //解绑
  handleUnBind = (data: any) => {
    const { dispatch } = this.props;

    dispatch({
      type: 'VehicleMng/getDataWithRes',
      payload: {
        url: '/msalcohollock/vehicle/monitor/state',
        vin: data.vin,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          if (res.data === 0) {
            this.setState({
              unBindVisible: true,
              formData: data,
            });
          } else if (res.data === 1) {
            Modal.warning({
              title: '解绑设备',
              content: `无法解绑,请先前往司机管理页面撤销车辆${data.vin}激活的监控`,
              okText: '确定',
              okButtonProps: {size: 'small'}
            });
          }
        }
      },
    });
  };
  //取消解绑
  cancelUnBind = () => {
    this.setState({
      unBindVisible: false,
      formData: {},
    });
  };
  //批量导入
  handleExport = () => {
    this.setState({
      exportVisible: true,
    });
  };
  closeExportModal = () => {
    this.setState({
      exportVisible: false,
    });
  };
  handleFreshPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'VehicleMng/getFetchPage',
      payload: {
        url: '/msalcohollock/vehicle/page',
        ...formValues,
      },
    });
  };

  //  删除
  handleDelete = (record: any) => {
    this.setState({
      confirmVisible: true,
      formData: record,
    });
  };
  closeConfirmModal = (ref = false) => {
    this.setState({
      confirmVisible: false,
      formData: {},
    });
    if (ref) {
      this.handleFreshPage();
    }
  };
  render() {
    const {
      VehicleMng: {
        pageData: { list, pagination },
      },
      loading,
      permissions,
      location: { pathname = '/' },
    } = this.props;
    const { formValues, modalVisible, formData, exportVisible, bindModalVisible, confirmVisible } =
      this.state;
    // const burningStatus = getDictOptionsByCode(this.context.dicData, 'burningStatus')

    const page = {
      current: pagination.pageNo || 1,
      pageSize: pagination.pageSize,
      total: pagination.totalSize,
    };

    const searchItems = [
      {
        title: 'VIN',
        type: 'input',
        key: 'vin',
        maxLength: 50,
        // style: "text-transform:uppercase",
        rules: [
          {
            required: false,
            message: '请输入英文及数字!',
            pattern: '^[a-zA-Z0-9]*$',
          },
        ],
        formItemProps: {
          normalize: (value, prevValue, prevValues) => {
            // 转大写
            return value.toUpperCase();
          },
        },
      },
      {
        title: '设备编号',
        type: 'input',
        key: 'code',
        maxLength: 50,
        placeholder: '手持机编号/控制盒编号',
        rules: [
          {
            required: false,
            // message: '请输入英文及数字、特殊字符，最多可输入50个字符',
            // pattern: /^[a-zA-Z0-9\s\w]+$/,
            message: '不能输入空字符!',
            pattern: /^\S+$/,
          },
        ],
      },
      {
        title: '设备绑定状态',
        type: 'select',
        key: 'bindingState',
        selectOptions: [
          { label: '未绑定', value: 0 },
          { label: '已绑定', value: 1 },
        ],
      },
      {
        title: '手持机标定状态',
        type: 'select',
        key: 'calibrationState',
        selectOptions: [
          { label: '有效', value: 0 },
          { label: '即将到期', value: 1 },
          { label: '已到期,宽限期内', value: 2 },
          { label: '已到期,锁止', value: 3 },
        ],
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => <span>共&nbsp;{page?.total}&nbsp;条</span>,
    };
    const bindingStateOption = ['未绑定', '已绑定'];
    const calibrationStateOption = ['有效', '即将到期', '已到期,宽限期内', '已到期,锁止'];
    const columns = [
      {
        title: 'VIN',
        dataIndex: 'vin',
      },
      {
        title: '车牌号',
        dataIndex: 'licencePlate',
      },
      {
        title: '控制盒编号',
        dataIndex: 'cboxCode',
      },
      {
        title: '手持机编号',
        dataIndex: 'handheldsCode',
      },
      {
        title: '所属车队',
        dataIndex: 'fleetName',
      },
      {
        title: '设备绑定状态',
        dataIndex: 'bindingState',
        render: (text: any, record: any) => {
          return bindingStateOption[text] || text;
        },
      },
      {
        title: '手持机标定状态',
        dataIndex: 'calibrationState',
        render: (text: any, record: any) => {
          return calibrationStateOption[text] || text;
        },
      },
      {
        title: '手持机标定到期时间',
        dataIndex: 'calibrationTime',
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 150,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '绑定设备',
              key: 'edit',
              auth: 'vehicleMng_doBind',
              hide: record.bindingState !== 0,
              onConfirm: () => {
                this.handleBind(record);
              },
            },
            {
              title: '解绑设备',
              key: 'unbind',
              auth: 'vehicleMng_doUnbind',
              // hide: record.bindingState === 0,
              onConfirm: () => {
                this.handleUnBind(record);
              },
            },
            {
              title: '设置车牌',
              key: 'set',
              auth: 'vehicleMng_doSet',
              onConfirm: () => {
                this.handleEdit(record);
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'vehicleMng_doDel',
              onConfirm: () => {
                this.handleDelete(record);
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
        },
      },
    ];

    const tableProps = {
      columns,
      dataSource: list,
      loading,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
      key: 'vin',
    };
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'VehicleMng/getFetchPage',
              url: '/msalcohollock/vehicle/page',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div className="my_newItem">
            {filterAuth('vehicleMng_doAdd', permissions, pathname) ? (
              <Button size="small" type="primary" onClick={this.handleAdd}>
                新增车辆
              </Button>
            ) : null}
            {filterAuth('vehicleMng_doExport', permissions, pathname) ? (
              <Button size="small" type="primary" onClick={this.handleExport}>
                批量导入
              </Button>
            ) : null}
          </div>
          <PateoTable
            extraHandle={true}
            currentName={'page'}
            pageSizeName={'size'}
            tableProps={tableProps}
            fetchParams={{ type: 'VehicleMng/getFetchPage', url: '/msalcohollock/vehicle/page' }}
            formValues={formValues}
          />
        </Card>
        <AddModel
          modalVisible={modalVisible}
          closeModal={this.closeModal}
          freshPage={this.handleFreshPage}
          formData={formData}
        ></AddModel>
        <ExportModal
          modalVisible={exportVisible}
          closeModal={this.closeExportModal}
          freshPage={this.handleFreshPage}
        ></ExportModal>
        <BindModel
          modalVisible={bindModalVisible}
          formData={formData}
          closeModal={this.closeBindModal}
          freshPage={this.handleFreshPage}
        ></BindModel>
        {/* <Modal
          // footer={footers}
          visible={this.state.unBindVisible}
          width={350}
          centered={true}
          onCancel={this.cancelUnBind}
          onOk={this.handleToUnBind}
          okButtonProps={{ loading: unBindloading }}
          title={'解绑设备'}
        >
          确定要解除车辆{formData.vin}与手持机、控制盒的绑定关系吗？
        </Modal> */}
        <UnbindModel
          modalVisible={this.state.unBindVisible}
          formData={formData}
          closeModal={this.cancelUnBind}
          freshPage={this.handleFreshPage}
        />
        <ConfirmDelModal
          formData={formData}
          modalVisible={confirmVisible}
          closeModal={this.closeConfirmModal}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(VehicleMng);
